package com.ruoyi.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class EasyExcelMapExportUtil {

    /**
     * 基于模板导出Map列表数据（无实体类）
     * @param response 响应对象
     * @param templatePath 模板路径（如"templates/user_template.xlsx"）
     * @param fileName 导出文件名（不含后缀）
     * @param dataList Map列表（每个Map对应一行数据，key对应模板占位符）
     * @param sheetName 工作表名称
     */
    public static void exportWithMap(
            HttpServletResponse response,
            String templatePath,
            String fileName,
            List<Map<String, Object>> dataList,
            String sheetName
    ) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + encodedFileName + ".xlsx");

        // 读取模板
        ClassPathResource resource = new ClassPathResource(templatePath);
        try (InputStream is = resource.getInputStream()) {
            // 构建ExcelWriter
            ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                    .withTemplate(is)
                    .build();

            // 配置工作表
            WriteSheet sheet = EasyExcel.writerSheet(sheetName).build();

            // 填充列表数据（"list"对应模板中的{list.姓名}，若模板是单条则直接fill(dataList.get(0), sheet)）
            writer.fill( dataList, sheet);

            // 完成导出
            writer.finish();
        }
    }
}

